var fs = require('fs');
var config = require('../../../config.json');
var ProjectProxy = require('../../../proxy/project.js');
var RepositoryAPI = require('./../local_repositories.js');
var EventProxy = require('eventproxy');
var zip = require('../../../common/zip.js');
var path = require('path');
var _ = require('lodash');
var logger = require('log4js').getLogger();
var request = require('request');
var readline = require('readline');
var waterfall = require('async-waterfall');
var removeDir = require('../../../common/removeDir.js');
var decompress = require('decompress');
var decompressUnzip = require('decompress-unzip');
var uuid = require('uuid');
var platform = require('os').platform();
var child_process = require('child_process');
var WorkspaceProxy = require('../../../proxy/workspace.js');
var Workspace = require('../../../models/workspace.js');
var sdp_agent = config.server_agent.host + ":" + config.server_agent.port;
var fireWorkspaceUpdate = require('./notify.js').fireWorkspaceUpdate;
var notifyEnzyme = require('./notify.js').notifyEnzyme;
var messageAgent = require("../../../common/message.js");

/**
 * 更新工作空间依赖
 * {workspace_id:工作空间id}
 * @param req
 * @param res
 * @param next
 */
exports.updateTarget = function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var task_id = uuid.v1();
    res.format_json({task_id: task_id}, 200);
    messageAgent.setMessage(task_id, {msg: '更新工作空间...', isCompleted: false, err: null});
    var work_id = req.body.work_id;
    Workspace.findOne({_id: work_id}).populate('project_id').exec(function (err, workspace) {
        if (err) {
            logger.error(err);
            messageAgent.setMessage(task_id, {msg: null, isCompleted: false, err: err});
        }
        request({
            url: sdp_agent + '/api/workspace/'+ workspace.project_id.namespace + "$" + workspace.project_id.name + "$" + workspace.work_name,
            method: "PUT",
            json: true,
            body: {
                work_name: workspace.work_name,
                project_name: workspace.project_id.name,
                namespace: workspace.project_id.namespace,
                //workspace_dependencies: workspace.dependencies,
                project_dependencies: workspace.project_id.dependencies
            }
        }, function (err, response, data) {
            if (data.code == 200) {
                if (data.data.task_id) {
                    messageAgent.getMessage(sdp_agent + "/api/workspace/" + workspace.project_id.namespace + "$" + workspace.project_id.name + "$" + workspace.work_name + "?task_id=" + data.data.task_id, function (msg) {
                        if (msg.err) {
                            logger.error(msg.err);
                            messageAgent.setMessage(task_id, {msg: null, isCompleted: false, err: err});
                        } else {
                            if (msg.isCompleted) {
                                waterfall([
                                    function (cb) {
                                        WorkspaceProxy.updateDependency(workspace._id, workspace.project_id.dependencies, function (err) {
                                            if (err) {
                                                logger.error("更新数据库工作空间依赖出错");
                                                messageAgent.setMessage(task_id, {msg: null, isCompleted: false, err: err});
                                            }
                                            logger.info("更新数据库工作空间依赖成功");
                                            cb(null);
                                        });
                                    },
                                    //7.触发外部监听
                                    function ( cb) {
                                        fireWorkspaceUpdate(workspace._id);
                                        cb(null);
                                    },
                                    //8.通知Enzyme
                                    function (cb) {
                                        notifyEnzyme(workspace.work_name, function (err) {
                                            if (err) {
                                                //如果是新建工作空间，失败是正常的
                                                logger.error(err);
                                                logger.info("通知Enzyme失败");
                                            } else {
                                                logger.info("通知Enzyme成功");
                                            }
                                            cb(null);
                                        })
                                    }
                                ], function (err, result) {
                                    if (err) {
                                        logger.error(err);
                                        messageAgent.setMessage(task_id, {msg: null, isCompleted: false, err: err});
                                    }else{
                                        messageAgent.setMessage(task_id, {msg: "更新成功", isCompleted: true, err: null});
                                    }
                                });
                            }
                        }

                    })
                }
            }
        });
    });
};


